package com.atlige.gzmall.ware.listener;

import com.alibaba.fastjson.TypeReference;
import com.atlige.common.constant.CartConstant;
import com.atlige.common.to.mq.OrderTo;
import com.atlige.common.to.mq.StockDetailTo;
import com.atlige.common.to.mq.StockLockedTo;
import com.atlige.common.utils.R;
import com.atlige.gzmall.ware.entity.WareOrderTaskDetailEntity;
import com.atlige.gzmall.ware.entity.WareOrderTaskEntity;
import com.atlige.gzmall.ware.service.WareSkuService;
import com.atlige.gzmall.ware.vo.OrderVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author: Jeremy lI
 * @description:
 * @date: created in 2021/7/10 0:30
 */
@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {
    @Autowired
    WareSkuService wareSkuService;

    /**
     * 库存自动解锁
     * // 2、下订单成功，库存锁成功，接下来的业务调用失败，导致订单回滚。之前锁定的库存需要自动解锁
     * 2、订单失败
     * 锁库存失败
     *
     * 只要解锁库存消息失败，一定要告诉服务器解锁失败
     * @param to
     * @param message
     */
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        try {
            wareSkuService.unlockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }

    }

    @RabbitHandler
    public void handleOrderClosedRelease(OrderTo to, Message message, Channel channel) throws IOException {
        System.out.println("订单关闭准备解锁库存");
        try {
            wareSkuService.unlockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }

    }
}
